<template>
  <div class="stats-container"> 
    <div class="stats-form stats-task-head">
      <biz-team-select is-auto-select-child collapse multiple class="stats-team-select biz-team-select" :value="tag" @input="chooseTeam" :fetch-func="fetchTeam"/>
    </div>

    <div class="stats-task-head" v-if="type === 'task-statistics'">
      <div class="stats-task-card">
        <p>{{ $t('common.task.type.taskPool') }}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.task.type.taskPool'), '')">{{headData.taskPoolCount | convertZero}}</a></h3>
      </div>
      <div class="stats-task-card">
        <p>{{$t('common.task.type.created')}}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.task.type.created'), `viewId=133d2ef7-19a8-11e7-8d4e-00163e304a25`)">{{headData.createdCount | convertZero}}</a></h3>
      </div>
      <div class="stats-task-card">
        <p>{{$t('common.task.type.allocated')}}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.task.type.allocated'), `viewId=12fcb144-1ea3-11e7-8d4e-00163e304a25`)">{{headData.allocatedCount | convertZero}}</a></h3>
      </div>
      <div class="stats-task-card">
        <p>{{$t('common.task.type.accepted')}}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.task.type.accepted'), `viewId=475e3328-1e63-11e7-8d4e-00163e304a25`)">{{headData.acceptedCount | convertZero}}</a></h3>
      </div>
      <div class="stats-task-card">
        <p>{{$t('common.task.type.processing')}}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.task.type.processing'), `viewId=06db63fe-5017-11e7-a318-00163e304a25`)">{{headData.processingCount | convertZero}}</a></h3>
      </div>
      <div class="stats-task-card">
        <p>{{ $t('common.base.todayFinished') }}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.base.todayFinished'), `viewId=5ac722d9-1e63-11e7-8d4e-00163e304a25`)">{{headData.todayFinish | convertZero}}</a></h3>
      </div>
      <div class="stats-task-card">
        <p>{{$t('common.task.type.exception')}}</p>
        <h3><a href="#" @click.prevent="openTaskList($event, $t('common.task.type.exception'), `viewId=a78cbfec-d7d2-420f-9a56-32a503702f2d`)">{{headData.unusualCount | convertZero}}</a></h3>
      </div>
    </div>

    <div class="stats-row" v-if="hasTeamChart && type === 'task-statistics'">
      <task-team-chart
        :team-id="teamId"
        @trackEvent="trackEventHandler"
        :exportAuth="exportAuth"
        :export-track="exportTrack"
        :chart-type="type">
      </task-team-chart>
    </div>

    <div class="stats-row" ref="taskCountChart" v-if="type === 'task-class'">
      <div class="stats-panel">
        <div class="stats-panel-head stats-form">
          <h3>{{ $t('report.taskView.text1') }}
            <el-popover trigger="hover">
              <div class="stats-popover-row">
                <div class="stats-popover-label">{{$t('report.taskProductChart.text4')}}：</div>
                <div class="stats-popover-text">{{ $t('report.taskView.des1') }}。</div>
              </div>
              <div class="stats-popover-row" v-if="!isBasicEditionHideProduct">
                <div class="stats-popover-label">{{$t('report.taskProductChart.text1')}}：</div>
                <div class="stats-popover-text">{{ $t('report.taskView.des2') }}。</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-label">{{$t('report.taskProductChart.text3')}}：</div>
                <div class="stats-popover-text">{{ $t('report.taskView.des3') }}。</div>
              </div>
              <div class="stats-popover-row">
                <div class="stats-popover-label">{{$t('report.taskProductChart.text2')}}：</div>
                <div class="stats-popover-text">{{ $t('report.taskView.des4') }}。</div>
              </div>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </h3>
          <div class="stats-form-group">
            <!-- <div id="date-range" class="stats-form-daterange">
              <span>{{timeStart}} - {{timeEnd}}</span> 
              <b class="caret"></b>
            </div> -->
            <date-picker @datePicker="datePicker" />
          </div>
        </div>
        <div class="stats-panel-body">
          <div class="stats-panel-title">
            <div class="stats-panel-product" v-if="isProductChart">
              <Treeselect 
                class="stats-tree-select"
                v-model="productTypeId" 
                :multiple="true"
                :clearAllText="''"
                :normalizer="normalizer"
                value-consists-of="ALL"
                :placeholder="$t('product.setting.qrCodeSet.associateDialog.pla1')"
                :options="catalogOption"
                :noResultsText="$t('common.base.tip.noData')"
                :limit="1"
                :limitText="count => `+ ${count}`"
                @input="delayParams"/>
            </div>
            <div style="text-align:center;">
              <div class="stats-btn-group">
                <button type="button" :class="{'stats-checked': chart == 'task-type-chart'}" 
                        @click="chooseChart('task-type-chart')">{{$t('common.label.taskTemplate')}}</button>
                <button type="button" :class="{'stats-checked': chart == 'task-product-chart'}" 
                        @click="chooseChart('task-product-chart')" v-if="!isBasicEditionHideProduct">{{$t('common.base.column.productType')}}</button>
                <button type="button" :class="{'stats-checked': chart == 'task-serviceType-chart'}" 
                        @click="chooseChart('task-serviceType-chart')">{{ $t('common.form.type.serviceType') }}</button>
                <button type="button" :class="{'stats-checked': chart == 'task-serviceContent-chart'}" 
                        @click="chooseChart('task-serviceContent-chart')">{{ $t('common.form.type.serviceContent') }}</button>
              </div>
            </div>
          </div>
          
          <keep-alive>
            <component
              :exportAuth="exportAuth"
              :is="chart"
              :chart-data="pieData"
              :chart-type="type"
              :time-start="timeStart"
              :time-end="timeEnd"
              @imageDownload="imageDownload"
              :export-track="exportTrack"
              :team-id="teamId">
            </component>
          </keep-alive>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* global AMap, moment*/
import _ from 'lodash';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import TaskTeamChart from './TaskTeamChart.vue';
import TaskTypeChart from './TaskTypeChart.vue';
import TaskProductChart from './TaskProductChart.vue';
import TaskServiceContentChart from './TaskServiceContentChart.vue';
import TaskServiceTypeChart from './TaskServiceTypeChart.vue'
import { isBasicEditionHideProduct } from '@shb-lib/version'
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
// api
import { cloneData } from '@src/api/ProductV2Api';

export default {
  name: 'task-view',
  data(){
    return {
      auths: {},
      teams: [],
      tag: [],

      headData: {
        acceptedCount: '--',
        allocatedCount: '--',
        completeCount: '--',
        createdCount: '--',
        processingCount: '--',
        taskPoolCount: '--',
        unusualCount: '--',
        todayFinish: '--'
      },

      pieData: {},
      timeStart: '',
      timeEnd: '',
      teamId: '',
      productTypeId: [],

      //
      chart: 'task-type-chart',
      type: '', // 判断入口

      catalogOption: [], // 产品类型数据
    };
  },
  computed: {
    /** 是否显示团队报表 */
    hasTeamChart(){
      let teams = this.teams || [];
      return teams.length > 0;
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct() 
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData?.auths?.REPORT_EXPORT || 0
    },
    // 是否是产品类型tab
    isProductChart(){
      return this.chart == 'task-product-chart';
    }
  },
  methods: {
    imageDownload() {
      this.type && this.$track.commonFn.chartTrack(this.type, 'DOWNLOAD_REPORT_IMAGE', this.$track)
    },
    exportTrack(isExportAll, hasTab = true) {
      let tab
      if(hasTab) tab = this.chart.toLocaleUpperCase().replaceAll('-', '_');
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.type,
        tab
      }, '*')
    },
    fetchTeam(params){
      return this.$http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    chooseChart(chart){
      this.trackEventHandler(chart);
      this.chart = chart;

      if(this.isProductChart){
        this.renderPie();
      }
    },
    chooseTeam(value){
      this.$tdOnEvent('pc：工单报表-选择团队事件');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      let tag = value
      this.tag = value;
      this.teamId = tag.map(item => {return item.id}).join(',');

      if (this.type !== 'task-class') this.initHead();
      if(this.type !== 'task-statistics') this.renderPie();

      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TEAM', this.$track)
    },
    async initHead(){
      try {
        let data = await this.fetchTaskStateCount();
        _.assign(this.headData, data);
      } catch (error) {
        console.log(error)
      }
    },
    fetchTaskStateCount(){
      return this.$http.post('/api/report/outside/stats/task/stateCount', {
        tagId: this.teamId
      });
    },
    fetchTaskCount(){
      let params = {
        tagId: this.teamId,
        productCatalogueIdList: this.isProductChart ? this.productTypeId : []
      };
      if (this.timeStart) params.timeStart = this.timeStart
      if (this.timeEnd) params.timeEnd = this.timeEnd
      
      return this.$http.post('/api/dataware/outside/statistics/task/count', params);
    },
    initPie(start, end){

      this.timeStart = start;
      this.timeEnd = end;

      this.renderPie();
    },
    chooseDate(start, end){
      this.timeStart = start;
      this.timeEnd = end;
      this.renderPie();
    },
    async renderPie(){
      try {
        let instance = this.$loading.show(this.$refs.taskCountChart);
        let { code, data } = await this.fetchTaskCount();
        instance.hide();
        if(code !== 200 ) return
        this.pieData = _.assign({}, this.pieData, data);
      } catch (error) {
        console.log(error)
      }
    },
    openTaskList(event, trackEventName, url) {
      this.trackEventHandler(trackEventName);
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: trackEventName === this.$t('common.task.type.taskPool') ? PageRoutesTypeEnum.PageTaskPoolList : PageRoutesTypeEnum.PageTaskList,
        params:url,
        fromId
      })
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      let msg = '';
      switch (type) {
      case this.$t('common.task.type.taskPool'):
        msg = 'pc：工单报表-工单池事件';
        break;
      case this.$t('common.task.type.created'):
        msg = 'pc：工单报表-待指派事件';
        break;
      case this.$t('common.task.type.allocated'):
        msg = 'pc：工单报表-已指派事件';
        break;
      case this.$t('common.task.type.accepted'):
        msg = 'pc：工单报表-已接受事件';
        break;
      case this.$t('common.task.type.processing'):
        msg = 'pc：工单报表-进行中事件';
        break;
      case this.$t('common.base.todayFinished'):
        msg = 'pc：工单报表-今日完成事件';
        break;
      case this.$t('common.task.type.exception'):
        msg = 'pc：工单报表-异常工单事件';
        break;
      case 'task-type-chart':
        msg = 'pc：工单报表-工单类型事件';
        break;
      case 'task-product-chart':
        msg = 'pc：工单报表-产品类型事件';
        break;
      case 'task-serviceType-chart':
        msg = 'pc：工单报表-服务类型事件';
        break;
      case 'task-serviceContent-chart':
        msg = 'pc：工单报表-服务内容事件';
        break;         
      case 'chooseDate':
        msg = 'pc：工单报表-日期选择事件';                                                   
      default:
        break;
      }
      this.$tdOnEvent(msg);
    },
    datePicker(data) {
      // 初始化趋势图
      this.initPie(data[0], data[1]);
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TIME', this.$track)
    },
    // 获取树结构
    async getCatalogOption () {
      try{
        let {code,result,message} = await cloneData();
        if(code === 0) {
          let ids = [];
          this.deleteEmpty(result, ids);
          
          this.productTypeId = ids;
          this.catalogOption = result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },

    // 删除空子集 并返回所有子集的id
    deleteEmpty (list, ids) {
      list.forEach(item => {
        ids.push(item.id);
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks, ids);
        }
      });
    },
    delayParams(){
      const t = setTimeout(() => {
        this.renderPie();
        clearTimeout(t);
      });
    },
    // 节点配置
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.tasks
      }
    },
  },
  mounted(){
    this.type = window.location.href.split('type=')[1]
    try {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      this.auths = initData?.auths || {};
      this.teams = initData?.teams || [];
    } catch (error) {
      console.error('initData 赋值失败')
    }
    this.getCatalogOption();

    if (this.type !== 'task-class') this.initHead();
  },
  components: {
    [TaskTeamChart.name]: TaskTeamChart,
    [TaskTypeChart.name]: TaskTypeChart,
    [TaskProductChart.name]: TaskProductChart,
    [TaskServiceTypeChart.name]: TaskServiceTypeChart,
    [TaskServiceContentChart.name]: TaskServiceContentChart,
    Treeselect
  }
}
</script>

<style lang="scss">
.stats-task-head{
  display: flex;
  flex-flow: row nowrap;
  padding: 5px 7.5px;
  justify-content: flex-end;
}

.stats-panel-body {
  .stats-panel-title {
    position: relative;
    .stats-panel-product {
      width: 320px;
      position: absolute;
      left: 17px;
      top: 50%;
      transform: translateY(-50%);
      z-index: 999;
    }
  }
}

.stats-task-card{
  flex: 1;
  margin-left: 15px;

  border-radius: 2px;
  background-color: #fff;
  text-align: center;

  p{
    padding: 15px 0 8px;
    margin: 0;
    font-size: 14px;
  }

  h3{
    font-weight: 400;
    font-size: 24px;
    line-height: 34px;
    margin: 0;
    padding: 5px 0;

    a{
      color: #2d9cf5;
    }
  }

  &:first-child{
    margin-left: 0;
  }
}

.stats-task-form{
  padding: 5px;
  justify-content: flex-end;
}

.stats-task-chart-wrap{
  
}

.stats-task-table-header{
  display: flex;
  flex-flow: row nowrap;
  padding: 5px;

  h3{
    font-size: 14px;
    flex: 1;
    margin: 0;
    line-height: 30px;
  }

  button{
    margin-left: 5px;
  }
}


#product-type-chart,
#task-type-chart,
#service-type-chart,
#service-content-chart{
  height: 520px;
}
</style>
